package io.dy.mq.producer;

import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFutureCallback;

import javax.annotation.PostConstruct;
import java.util.UUID;

/**
 * @author dmj
 * @date 2024年04月18日 下午4:49
 * topic - 生产者
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class SafeTopicProducer implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnsCallback{

    private final RabbitTemplate rabbitTemplate;


    @PostConstruct
    public void init(){
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnsCallback(this);
    }

    public boolean send(Object msg){
        String randomStr = UUID.randomUUID().toString();
        log.info("唯一标识:{}", randomStr);
        CorrelationData correlationData = new CorrelationData(randomStr);
        rabbitTemplate.convertAndSend("dy.topic.exchange", "dy.order", JSONObject.toJSONString(msg), correlationData);
        return true;
    }

    public boolean sendErrorForExchange(Object msg){
        String randomStr = UUID.randomUUID().toString();
        log.info("唯一标识:{}", randomStr);
        CorrelationData correlationData = new CorrelationData(randomStr);
        rabbitTemplate.convertAndSend("dy.topic.exchange01", "sy.order", JSONObject.toJSONString(msg), correlationData);
        return true;
    }

    public boolean sendErrorForQueue(Object msg){
        String randomStr = UUID.randomUUID().toString();
        log.info("唯一标识:{}", randomStr);
        CorrelationData correlationData = new CorrelationData(randomStr);
        rabbitTemplate.convertAndSend("dy.topic.exchange", "sy.order", JSONObject.toJSONString(msg), correlationData);
        return true;
    }

    public boolean sendInnerConfirm(Object msg){
        String randomStr = UUID.randomUUID().toString();
        log.info("唯一标识:{}", randomStr);
        CorrelationData correlationData = new CorrelationData(randomStr);
        correlationData.getFuture().addCallback(
                result->{
                            if(result.isAck()){
                                log.info("消息成功投递到交换机！消息ID: {}", correlationData.getId());
                            }else{
                                log.info("消息投递到交换机失败！消息ID：{}", correlationData.getId());
                                log.info("准备重发！！！");
                            }
                        },
                ex->{
                        log.info("消息发送异常，异常信息:{}", ex.getMessage());
                        log.info("重发或者记录消息日志");
                    }
        );
        rabbitTemplate.convertAndSend("dy.topic.exchange01", "dy.order", JSONObject.toJSONString(msg), correlationData);
        return true;
    }


    /**
     * 不管成功与否 都会调用 此处定义的是全局的
     * @param correlationData 对象内部只有一个 id 属性，用来表示当前消息的唯一性
     * @param ack 消息投递到broker 的状态，true表示成功 false表示失败
     * @param cause 表示投递失败的原因
     *  注意: 消息被 broker 接收到只能表示已经到达 MQ服务器，并不能保证消息一定会被投递到目标 queue 里。所以接下来需要用到 returnCallback
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        log.info("消息标识:{}, 发送成功确认:{}, 错误原因:{}", correlationData, ack, cause);
    }

    /**
     * 如果消息未能投递到目标 queue 里将触发回调 returnCallback ，一旦向 queue 投递消息未成功，这里一般会记录下当前消息的详细投递数据，方便后续做重发或者补偿等操作
     * @param returnedMessage 消息体
     */
    @Override
    public void returnedMessage(ReturnedMessage returnedMessage) {
        log.info("回调信息:" + returnedMessage);
    }
}
